<?php

namespace App\Services\Info;

use App\Common\Helper;
use App\Common\Http\Basics\Fail;
use App\Dao\BaseDao;
use Closure;
trait TraitFunc
{
    private array|null $info = null;
    private int|string|null $_id = null;
    protected Closure|null $nullRes = null;

    public final function getInfo(string $primary_key,string $orm,array $field)
    {
        $this->_id =   $this->getId($primary_key);
        $this->primary_key =   $primary_key;
        if ($this->info === null) {
            if ($this->getAndCheckInfo($field, $this->loginInfo,$orm )) $this->info = $this->loginInfo;
        } else {
            $this->getAndCheckInfo($field, $this->info,$orm);
        }
        return $this->info === null ? $this->response() : Helper::keyVal($this->info, $field);
    }

    private final function response(){
        $nullRes = $this->nullRes;
        return $nullRes !== null ? $nullRes() : Helper::throwHttpCustom(Fail::INFO_NOT_DEFINED);
    }

    private final function getId($primary_key)
    {
        return  $this->loginInfo[$primary_key] ??  Helper::throwHttpCustom(Fail::INFO_NOT_DEFINED);
    }

    private final function getAndCheckInfo(array $field,array|null $info,string $orm)
    {
        $check = true;
        if($info === null ) $info = [];
        foreach (array_keys($field) as $val) {
            if (!isset($info[$val])) {
                $check = false;
                $this->info =  (new $orm)->find($this->_id)?->toArray();
                break;
            }
        }
        return  $check;
    }

}
